﻿// ------------------------------------------------------------------------
// 项目名称：Canroc.Net 
// 版权归属：Canroc（https://gitee.com/canroc）
//
// 许可证信息
// Canroc.Net项目主要遵循 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-APACHE 文件。
//
// 使用条款：
// 1.使用本项目应遵守相关法律法规和许可证的要求。
// 2.不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动。
// 3.任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任
//
// 免责声明
// 对于因使用本代码而产生的任何直接、间接、偶然、特殊或后果性损害，我们不承担任何责任。
//
// 其他重要信息
// Canroc.Net 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。
// ------------------------------------------------------------------------

using Canroc.Net.Application.SysDictService.Dto;

// ReSharper disable once CheckNamespace
namespace Canroc.Net.Application.SysDictService;

/// <summary>
///     系统字典应用服务
/// </summary>
[ApiDescriptionSettings("System")]
public partial class SysDictAppService(
    SqlSugarRepository<SysDictType> typeRep,
    SqlSugarRepository<SysDictData> dataRep) : IDynamicApiController, ITransient
{
    /// <summary>
    ///     添加系统字典
    /// </summary>
    /// <param name="data">表单数据</param>
    /// <returns></returns>
    public async Task<bool> AdditionAsync(DictInput data)
    {
        if (data.DictType == DictTypeEnum.Classification)
        {
            SysDictType entity = new() { Code = data.Code, Name = data.Name };
            return await typeRep.InsertAsync(entity);
        }
        else
        {
            SysDictData entity = new()
            {
                TypeId = data.TypeId,
                Label = data.Label,
                Value = data.Value,
                Remarks = data.Remarks,
                Sort = data.Sort
            };
            return await dataRep.InsertAsync(entity);
        }
    }

    /// <summary>
    ///     编辑系统字典
    /// </summary>
    /// <param name="data">表单数据</param>
    /// <returns></returns>
    public async Task<bool> EditAsync(DictInput data)
    {
        if (data.DictType == DictTypeEnum.Classification)
        {
            var entity = await typeRep.GetByIdAsync(data.TypeId);
            entity.Name = data.Name;
            entity.Code = data.Code;
            return await typeRep.UpdateAsync(entity);
        }
        else
        {
            var entity = await dataRep.GetByIdAsync(data.Id);
            entity.Label = data.Label;
            entity.Value = data.Value;
            entity.Remarks = data.Remarks;
            entity.Sort = data.Sort;
            return await dataRep.UpdateAsync(entity);
        }
    }

    /// <summary>
    ///     编辑系统字典状态
    /// </summary>
    /// <param name="data">请求模板</param>
    public async Task<bool> EnableAsync(InputModel data)
    {
        return await dataRep.UpdateAsync(d => new SysDictData { IsEnable = SqlFunc.IIF(d.IsEnable, false, true) },
            d => d.Id == data.Id);
    }

    /// <summary>
    ///     删除系统字典
    /// </summary>
    /// <param name="data">请求参数</param>
    public async Task<bool> DelAsync(DeleteInputModel data)
    {
        return await dataRep.UpdateAsync(d => new SysDictData { IsDelete = true }, d => data.Ids.Contains(d.Id));
    }

    /// <summary>
    ///     获取系统字典
    /// </summary>
    /// <param name="id">主键</param>
    public async Task<DictOutput?> GetDataAsync(Guid id)
    {
        return await dataRep
            .AsQueryable()
            .LeftJoin<SysDictType>((d, t) => d.TypeId == t.Id)
            .Where(d => d.Id == id)
            .Select((d, t) => new DictOutput
            {
                Id = d.Id,
                DictType = DictTypeEnum.Data,
                Name = t.Name,
                Code = t.Code,
                TypeId = d.TypeId,
                Label = d.Label,
                Value = d.Value,
                Remarks = d.Remarks,
                Sort = d.Sort,
                IsEnable = d.IsEnable,
                CreateTime = d.CreateTime
            })
            .FirstAsync();
    }

    /// <summary>
    ///     获取字典分类列表
    /// </summary>
    [Route("dict-type")]
    public async Task<List<DictTypeOutput>?> GetDictTypeListAsync()
    {
        return await typeRep.AsQueryable().OrderBy(d => d.CreateTime).Select<DictTypeOutput>().ToListAsync();
    }

    /// <summary>
    ///     获取系统字典列表
    /// </summary>
    /// <param name="query">查询参数</param>
    public async Task<PageModel<DictOutput>> GetPageAsync([FromQuery] DictPageQuery query)
    {
        return await dataRep
            .AsQueryable()
            .LeftJoin<SysDictType>((d, t) => d.TypeId == t.Id)
            .WhereIF(!query.Label.IsNullOrEmpty(), d => d.Label.Contains(query.Label))
            .WhereIF(query.TypeId.HasValue, d => d.TypeId == query.TypeId)
            .WhereIF(query.IsEnable.HasValue, d => d.IsEnable == query.IsEnable)
            .Select((d, t) => new DictOutput
            {
                Id = d.Id,
                DictType = DictTypeEnum.Data,
                Name = t.Name,
                Code = t.Code,
                TypeId = d.TypeId,
                Label = d.Label,
                Value = d.Value,
                Remarks = d.Remarks,
                Sort = d.Sort,
                IsEnable = d.IsEnable,
                CreateTime = d.CreateTime
            })
            .MergeTable()
            .OrderByPropertyName(query.OrderField, query.IsAscending ? OrderByType.Asc : OrderByType.Desc)
            .ToPageAsync(query.PageIndex, query.PageSize);
    }

    /// <summary>
    ///     获取系统字典下拉选项
    /// </summary>
    /// <param name="code">分类编码</param>
    /// <returns></returns>
    public async Task<List<SelectOptionOutputModel>?> GetSelectOptionAsync(string code)
    {
        return await dataRep
            .AsQueryable()
            .LeftJoin<SysDictType>((d, t) => d.TypeId == t.Id)
            .Where((d, t) => t.Code == code)
            .OrderBy(d => d.Sort)
            .Select(d => new SelectOptionOutputModel { Label = d.Label, Value = d.Value })
            .ToListAsync();
    }
}